import requests as rq
import qrcode
import re
from concurrent.futures.thread import ThreadPoolExecutor

# 记录线程池中的任务完成个数
finish = []


class SearchVip():
    '''搜索百度云送vip活动'''
    def __init__(self, url):
        self.__url = url
        self.__nums = []

    def get_url(self, start=0, end=10000):
        '''获取活动url'''
        for _ in range(start, end):
            url = f'{self.__url}{_}'
            try:
                html = rq.get(url=url)
            except Exception:
                continue
            # html.url是重定向后的网址，如果没重定向就是有效活动
            if url == html.url:
                # 如果能匹配到内容就是送vip活动
                if re.search(r'<title.*?>.*?- 会员狂欢季</title>', html.text):
                    self.__nums.append(_)
        finish.append(0)

    def get_nums(self):
        return self.__nums

    def set_qrcode(self, num):
        '''生成活动链接二维码'''
        return qrcode.make(f'{self.__url}{num}')

    def save(self, path):
        '''保存所有活动的链接和二维码'''

        for n in self.__nums:
            self.set_qrcode(n).save(f'{path}\img\{n}.png')
            with open(f'{path}/url.txt', 'a') as f:
                f.write(f'{self.__url}{n}\r')


def search(start, end):

    url_ = 'https://pan.baidu.com/component/view/'
    pool = ThreadPoolExecutor(8)
    s = SearchVip(url_)
    # 扔进池子中的任务数
    n = 0
    for _ in range(start, end, 8):
        pool.submit(s.get_url, _, _ + 7)
        n += 1
    if _ < end:
        pool.submit(s.get_url, _, end)
    pool.shutdown(wait=False)
    return s, n + 1


if __name__ == '__main__':
    s = SearchVip('https://pan.baidu.com/component/view/')
    s.get_url(1500, 1600)
    img = s.get_nums()[0]
    
    print(s.get_nums())
    # s.save('D:\Temp')
